package com.kartoshka.painters 
{
	import flash.geom.Matrix;
	import flash.display.Graphics;

	import com.kartoshka.interfaces.IPainter;
	import com.kartoshka.painters.NullPainter;

	/**
	 * @author Alexander Zats, 2009
	 */
	public class BackgroundGradientPainter extends NullPainter implements IPainter 
	{

		protected var _colors : Array;
		protected var _alphas : Array;
		protected var _ratios : Array;
		protected var _rotation : Number;
		protected var _type : String;

		public function BackgroundGradientPainter( colors : Array = null, rotation : Number = Math.PI / 2, cornerRadius : Number = 0 )
		{
			super( );
			
			this.cornerRadius = cornerRadius;
			this.colors = colors ? colors : [ 0xEDEDED, 0x757575 ];
			this.rotation = rotation;
			
			_type = "linear";
		}

		public function set colors( value : Array ) : void
		{
			if ( ! value )
			{
				_colors = null;
				return;
			}
			_colors = value;
			_alphas = [];
			_ratios = [];
			for ( var i : int = 0; i < value.length ; i++ )
			{
				_alphas[ _alphas.length ] = 1;
				_ratios[ _ratios.length ] = i / ( value.length - 1 ) * 0xFF;
			}
		}

		public function get colors() : Array
		{
			return _colors;
		}

		public function set alphas( value : Array ) : void
		{
			_alphas = value;
		}

		public function get alphas() : Array
		{
			return _alphas;
		}

		public function set ratios( value : Array ) : void
		{
			_ratios = value;
		}

		public function get ratios() : Array
		{
			return _ratios;
		}

		public function set rotation( value : Number ) : void
		{
			value %= Math.PI * 2;
			
			_rotation = value;
		}

		public function get rotation() : Number
		{
			return _rotation;
		}

		public function set type( value : String ) : void
		{
			if ( value != "radial" ) value = "linear";
			_type = value;
		}

		public function get type() : String
		{
			return _type;
		}

		override public function draw(graphics : Graphics, width : Number, height : Number) : void
		{
			var gradientMatrix : Matrix = new Matrix( );
			gradientMatrix.createGradientBox( width, height, _rotation );
			graphics.beginGradientFill( _type, _colors, _alphas, _ratios, gradientMatrix );
			_cornerRadius ? graphics.drawRoundRect( 0, 0, width, height, _cornerRadius, _cornerRadius ) : graphics.drawRect( 0, 0, width, height );
			graphics.endFill( );
		}
	}
}
